#!/usr/bin/env python3
import os
import subprocess
import shutil
from pathlib import Path
import logging
import sys
import traceback
from datetime import datetime
import json

class ProjectBuilder:
    def __init__(self):
        self.project_root = Path.cwd()
        self.setup_logging()
        self.build_info = {
            'start_time': datetime.now().isoformat(),
            'status': 'initialized',
            'errors': [],
            'warnings': []
        }

    def setup_logging(self):
        """设置日志配置"""
        log_dir = Path('logs')
        log_dir.mkdir(exist_ok=True)
        log_file = log_dir / f'build_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - [%(name)s] - %(message)s',
            handlers=[
                logging.StreamHandler(),
                logging.FileHandler(log_file, encoding='utf-8')
            ]
        )
        self.logger = logging.getLogger('ProjectBuilder')

    def create_directory_structure(self):
        """创建正确的目录结构"""
        try:
            base_dirs = {
                'main': self.project_root / 'src/main/java/com/game/doudizhu',
                'test': self.project_root / 'src/test/java/com/game/doudizhu',
                'resources': self.project_root / 'src/main/resources',
                'test_resources': self.project_root / 'src/test/resources'
            }
            
            for dir_path in base_dirs.values():
                dir_path.mkdir(parents=True, exist_ok=True)
            
            self.logger.info("Directory structure created successfully")
            return base_dirs
        except Exception as e:
            self.log_error("Failed to create directory structure", e)
            return None

    def fix_package_structure(self):
        """修复包结构"""
        try:
            self.logger.info("Starting to fix package structure...")
            
            # 创建目录结构
            base_dirs = self.create_directory_structure()
            if not base_dirs:
                return False
            
            # 移动所有Java文件到正确的包目录
            for java_file in self.project_root.rglob("*.java"):
                if "target" in str(java_file):
                    continue
                
                package_name = self.get_package_name(java_file)
                if package_name:
                    # 确定目标目录
                    if "test" in str(java_file):
                        base_dir = base_dirs['test']
                    else:
                        base_dir = base_dirs['main']
                    
                    # 根据包名创建子目录
                    package_parts = package_name.split('.')[-1:]
                    target_dir = base_dir
                    for part in package_parts:
                        target_dir = target_dir / part
                        target_dir.mkdir(exist_ok=True)
                    
                    # 移动文件
                    target_file = target_dir / java_file.name
                    if target_file != java_file:
                        shutil.copy2(java_file, target_file)
                        self.logger.info(f"Moved {java_file.name} to {target_file}")
            
            self.logger.info("Package structure fixed successfully")
            return True
        except Exception as e:
            self.log_error("Failed to fix package structure", e)
            return False

    def get_package_name(self, file_path):
        """从Java文件中提取包名"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                for line in content.split('\n'):
                    if line.startswith('package '):
                        return line.split()[1].rstrip(';')
        except Exception as e:
            self.log_error(f"Error reading file {file_path}", e)
        return None

    def build_project(self):
        """构建项目"""
        try:
            self.logger.info("Starting project build...")
            
            # 清理项目
            self.run_maven_command("clean")
            
            # 编译项目
            self.run_maven_command("compile")
            
            # 运行测试
            self.run_maven_command("test")
            
            # 打包
            self.run_maven_command("package -DskipTests")
            
            self.logger.info("Build completed successfully")
            return True
        except Exception as e:
            self.log_error("Build failed", e)
            return False

    def run_maven_command(self, command):
        """运行Maven命令"""
        try:
            self.logger.info(f"Running Maven command: {command}")
            result = subprocess.run(
                f"mvn {command}",
                shell=True,
                check=True,
                capture_output=True,
                text=True
            )
            self.logger.info(f"Maven {command} completed successfully")
            if result.stdout:
                self.logger.debug(result.stdout)
            return True
        except subprocess.CalledProcessError as e:
            self.log_error(f"Maven {command} failed: {e.output}", e)
            raise

    def log_error(self, message, exception=None):
        """记录错误信息"""
        self.logger.error(message)
        if exception:
            self.logger.error(traceback.format_exc())
        self.build_info['errors'].append({
            'message': message,
            'timestamp': datetime.now().isoformat(),
            'traceback': traceback.format_exc() if exception else None
        })

def main():
    builder = ProjectBuilder()
    success = True
    
    try:
        # 修复包结构
        if not builder.fix_package_structure():
            raise Exception("Failed to fix package structure")
        
        # 构建项目
        if not builder.build_project():
            raise Exception("Failed to build project")
        
        builder.build_info['status'] = 'success'
        
    except Exception as e:
        builder.log_error("Build process failed", e)
        success = False
        builder.build_info['status'] = 'failed'
    
    # 保存构建信息
    with open('build-info.json', 'w', encoding='utf-8') as f:
        json.dump(builder.build_info, f, indent=2, ensure_ascii=False)
    
    sys.exit(0 if success else 1)

if __name__ == "__main__":
    main()